<template>
	<div >
		<div class="system-user-search mb15">
			<el-form :model="param.dataForm" :inline="true" ref="queryFormRef" @keyup.enter.native="loadList">
				<el-row>
					<el-col :span="8">
							<el-form-item label="编号" prop="classCode">
								<el-input  v-model="param.dataForm.classCode" clearable/>
							</el-form-item>
					</el-col>
					<el-col :span="8">
							<el-form-item label="名称" prop="className">
								<el-input  v-model="param.dataForm.className" clearable/>
							</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-button type="primary" class="ml7" @click="loadList">
							<el-icon>
								<ele-Search />
							</el-icon>
							查询
						</el-button>
						<el-button type="primary" class="ml10" @click="reSetForm(queryFormRef)">
							<el-icon>
								<ele-Refresh />
							</el-icon>
							重置
						</el-button>
					</el-col>
				</el-row>
			</el-form>
		</div>
		<div class="btnStyle">
			<el-button type="success" icon="ele-Plus" @click="addOrUpdateHandle()">新增</el-button>
			<el-button type="primary" icon="ele-Edit" @click="updateHandle()" :disabled="dataListSelections.length !== 1">修改</el-button>
			<el-button type="danger" icon="ele-Delete" @click="deleteHandle()" :disabled="dataListSelections.length <= 0">删除</el-button>
		</div>
		<el-table :data="dataList" @selection-change="selectionChangeHandle" style="width: 100%">
			<el-table-column prop="id" type="selection" header-align="center" align="center" width="50"/>
			<el-table-column prop="classCode" header-align="center" align="center" label="类型编码"/>
			<el-table-column prop="className" header-align="center" align="center" label="类型名称"/>
			<el-table-column prop="dataCode" header-align="center" align="center" label="键值"/>
			<el-table-column prop="dataName" header-align="center" align="center" label="名称"/>
			<el-table-column prop="dataOrder" header-align="center" align="center" label="排序"/>
			<el-table-column prop="state" header-align="center" align="center" label="状态" :formatter="formatStatus"/>
			<el-table-column label="操作" show-overflow-tooltip width="140">
				<template #default="scope">
					<el-button type="primary" link @click="updateHandle(scope.row)">修改</el-button>
					<el-button type="primary" link @click="deleteHandle(scope.row.id)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>
		<el-pagination
			@size-change="onHandleSizeChange"
			@current-change="onHandleCurrentChange"
			:pager-count="5"
			:page-sizes="[10, 50, 200]"
			v-model:current-page="param.page"
			background
			v-model:page-size="param.limit"
			layout="total, sizes, prev, pager, next, jumper"
			:total="total" small>
		</el-pagination>
		<el-dialog :close-on-click-modal="false" :title="!submitForm.id ? '新增' : '修改'" ref="addOrUpdate" v-model="addOrUpdateVisible">
			<el-form :model="submitForm" :rules="submitFormRule" ref="ruleFormRef" @keyup.enter.native="dataFormSubmit" label-width="120px">
				<el-form-item label="类型编号" prop="classCode">
					<el-input v-model="submitForm.classCode" placeholder="类型编号" maxlength="20"></el-input>
				</el-form-item>
				<el-form-item label="类型名称" prop="className">
					<el-input v-model="submitForm.className" placeholder="类型名称" maxlength="50"></el-input>
				</el-form-item>
				<el-form-item label="键值" prop="dataCode">
					<el-input v-model="submitForm.dataCode" placeholder="键值" maxlength="20"></el-input>
				</el-form-item>
				<el-form-item label="名称" prop="dataName">
					<el-input v-model="submitForm.dataName" placeholder="名称" maxlength="50"></el-input>
				</el-form-item>
				<el-form-item label="排序" prop="dataOrder">
					<el-input v-model="submitForm.dataOrder" placeholder="排序" :maxlength="4" :min="1" :max="9999" :step="1" type="number"/>
				</el-form-item>
				<el-form-item label="状态" prop="state">
					<DicSelect v-model="submitForm.state" placeholder="请选择" dicCode="1001" :excludeIsKey="['100103']" style="width:100%"></DicSelect>
					<!-- <el-select v-model="submitForm.state" placeholder="请选择状态" style="width:100%">
						<template v-for="(item,index) in dataDictionaryList['1001']">
							<el-option :key="index" :label="item" :value="index" v-if="'100103' != index"/>
						</template>
					</el-select> -->
				</el-form-item>
				<el-form-item label="上级字典" prop="parentName">
					<el-input placeholder="请选择上级字典" v-model="submitForm.parentName" :disabled="true">
						<template #append>
							<el-button icon="ele-Search" @click="parentSearch()" />
						</template>
					</el-input>
				</el-form-item>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="addOrUpdateVisible = false">取消</el-button>
					<el-button type="primary" @click="dataFormSubmit(ruleFormRef)">确定</el-button>
				</span>
			</template>
		</el-dialog>
		<el-dialog :close-on-click-modal="false" title="选择上级字典" width="40%" v-model="visibleSelect">
			<el-form :model="paramSelect.dataForm" :inline="true" ref="querySelectFormRef">
				<el-row>
					<el-col :span="8">
							<el-form-item label="编号" prop="classCode">
								<el-input  v-model="paramSelect.dataForm.classCode" clearable/>
							</el-form-item>
					</el-col>
					<el-col :span="8">
							<el-form-item label="名称" prop="className">
								<el-input  v-model="paramSelect.dataForm.className" clearable/>
							</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-button type="primary" class="ml7" @click="loadListSelect">
							<el-icon>
								<ele-Search />
							</el-icon>
							查询
						</el-button>
						<el-button type="primary" class="ml10" @click="reSetFormSelect(querySelectFormRef)">
							<el-icon>
								<ele-Refresh />
							</el-icon>
							重置
						</el-button>
					</el-col>
				</el-row>
			</el-form>
			<el-table :data="dataListSelect" style="width: 100%">
				<el-table-column prop="classCode" header-align="center" align="center" label="类型编码"/>
				<el-table-column prop="className" header-align="center" align="center" label="类型名称"/>
				<el-table-column prop="dataCode" header-align="center" align="center" label="键值"/>
				<el-table-column prop="dataName" header-align="center" align="center" label="名称"/>
				<el-table-column prop="dataOrder" header-align="center" align="center" label="排序"/>
				<el-table-column prop="state" header-align="center" align="center" label="状态" :formatter="formatStatus"/>
				<el-table-column label="操作" show-overflow-tooltip width="140">
					<template #default="scope">
						<el-button type="primary" link @click="selectParent(scope.row)">选择</el-button>
					</template>
				</el-table-column>
			</el-table>
			<el-pagination
				@size-change="onSelectSizeChange"
				@current-change="onSelectCurrentChange"
				:pager-count="5"
				:page-sizes="[10, 50, 200]"
				v-model:current-page="paramSelect.page"
				background
				v-model:page-size="paramSelect.limit"
				layout="total, sizes, prev, pager, next, jumper"
				:total="totalSelect">
			</el-pagination>
		</el-dialog>
	</div>
</template>

<script lang="ts">
import { ref, toRefs, reactive, onMounted, defineComponent } from 'vue'
import type { FormInstance } from 'element-plus'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import {systemApi} from '/@/api/systemapi'
import { getCodeList } from '/@/utils/cacheDict'
export default defineComponent({
	name: 'systemDic',
	setup () {
		const state = reactive({
			listLoading: false,
			listSelectLoading: false,
			dataList: [],
			dataListSelect: [],
			dataDictionaryList: {},
			dataListSelections: [],
			total: 0,
			totalSelect: 0,
			param: {
				page: 1,
				limit: 10,
				dataForm: {
					classCode: '',
					className: ''
				}
			},
			paramSelect: {
				page: 1,
				limit: 10,
				dataForm: {
					classCode: '',
					className: ''
				}
			},
			addOrUpdateVisible: false,
			visibleSelect: false,
			submitForm: {
				id: '',
				classCode: '',
				className: '',
				dataCode: '',
				dataName: '',
				dataOrder: '',
				state: '',
				parentId: '',
				parentName: ''
			},
			submitFormRule: {
				classCode: [{ required: true, message: '类型编码不能为空', trigger: 'blur' }],
				className: [{ required: true, message: '类型名称不能为空', trigger: 'blur' }],
				dataCode: [{ required: true, message: '键值不能为空', trigger: 'blur' }],
				dataName: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
				dataOrder: [{ required: true, message: '排序不能为空', trigger: 'blur' }],
				state: [{ required: true, message: '状态不能为空', trigger: 'change' }]
			}
		})
		// 页面加载时
		onMounted(() => {
			// 数据字典
			getCodeList(state, ['1001'])
			// 列表查询
			loadList()
		})
		const queryFormRef = ref<FormInstance>()
		const querySelectFormRef = ref<FormInstance>()
		const ruleFormRef = ref<FormInstance>();
		//查询
		const loadList = () => {
			state.listLoading = true
			systemApi().getDicList(state.param).then(data => {
				if (data && data.code === 0) {
					state.dataList = data.page.list
					state.total = data.page.totalCount
				} else {
					state.dataList = []
					state.total = 0
				}
			}).catch(() => {
			}).finally(() => {
				state.listLoading = false
			})	
		}
		const loadListSelect = () => {
			state.listSelectLoading = true
			systemApi().getDicList(state.paramSelect).then(data => {
				if (data && data.code === 0) {
					state.dataListSelect = data.page.list
					state.totalSelect = data.page.totalCount
				} else {
					state.dataListSelect = []
					state.totalSelect = 0
				}
			}).catch(() => {
			}).finally(() => {
				state.listSelectLoading = false
			})	
		}
		//重置
		const reSetForm = (formEl: FormInstance | undefined) => {
			if (!formEl) return
			formEl.resetFields()
			state.param.page = 1
			loadList()
		}
		//重置
		const reSetFormSelect = (formEl: FormInstance | undefined) => {
			if (!formEl) return
			formEl.resetFields()
			state.paramSelect.page = 1
			loadListSelect()
		}
		const selectionChangeHandle = (val:any) => {
			state.dataListSelections = val
		}
		// 分页改变
		const onHandleSizeChange = (val: number) => {
			state.param.limit = val;
			loadList()
		}
		// 分页改变
		const onHandleCurrentChange = (val: number) => {
			state.param.page = val;
			loadList()
		}
		// 分页改变
		const onSelectSizeChange = (val: number) => {
			state.paramSelect.limit = val;
			loadListSelect()
		}
		// 分页改变
		const onSelectCurrentChange = (val: number) => {
			state.paramSelect.page = val;
			loadListSelect()
		}
		
		const formatStatus = (row: any, column: any, cellValue: string | number, index: number) => {
			if(Object.keys(state.dataDictionaryList).length>0){
				if (cellValue) {
				return state.dataDictionaryList['1001'][cellValue];
				}
			}
		}
		//打开新增弹窗
		const addOrUpdateHandle = () => {
			state.submitForm = {
				id: '',
				classCode: '',
				className: '',
				dataCode: '',
				dataName: '',
				dataOrder: '',
				state: '',
				parentId: '',
				parentName: ''
			}
			state.addOrUpdateVisible = true
		}
		//打开新增弹窗
		const updateHandle = (row: any | undefined) => {
			state.submitForm = {
				id: '',
				classCode: '',
				className: '',
				dataCode: '',
				dataName: '',
				dataOrder: '',
				state: '',
				parentId: '',
				parentName: ''
			}
			let selectId = ''
			if(!row){
				selectId = state.dataListSelections[0].id
				state.submitForm = state.dataListSelections[0]
			} else {
				state.submitForm = row
				selectId = row.id
			}
			systemApi().getDicInfoById(selectId).then(data => {
				if (data && data.code === 0) {
					state.submitForm = data.dic
				}
            })
			state.addOrUpdateVisible = true
			
		}
		//打开新增弹窗
		const deleteHandle = (id: string | undefined) => {
			var ids = id ? [id] : state.dataListSelections.map(item => {
				return item.id
			})
			if (!ids) {
				ElMessage.error('请选择记录！')
				return
			}
			ElMessageBox.confirm('是否确定删除所选记录', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
			}).then(() => {
				systemApi().deleteDic(ids).then(data => {
					if (data && data.code === 0) {
						ElMessage.success('删除成功')
						loadList();
					} else {
						ElMessage.error(data.msg)
					}
				}).catch(() => {
					ElMessage.error("删除失败")
				})
			})
		}

		const parentSearch = () => {
			loadListSelect()
			state.visibleSelect = true
		}

		const selectParent = (row: any | undefined) => {
			state.submitForm.parentId = row.id
			state.submitForm.parentName = row.className + '/' + row.dataName
			state.visibleSelect = false
		}

		const dataFormSubmit = (formEl: FormInstance | undefined) => {
			if (!formEl) return
			formEl.validate((valid: boolean) => {
				if (valid) {
					// 提交数据
					const loading = ElLoading.service({
						lock: true,
						text: '处理中',
						background: 'rgba(0, 0, 0, 0.7)',
					})
					if(!state.submitForm.id) {
						// 新增
						systemApi().saveDic(state.submitForm).then((data) => {
							if (data && data.code === 0) {
								ElMessage.success('保存成功')
								// 列表查询
								loadList()
								state.addOrUpdateVisible = false
							} else {
								ElMessage.error(data.msg)
							}
						}).catch(() => {
							ElMessage.error('保存失败')
						}).finally(() => {
							loading.close()
						})
					} else{
						systemApi().updateDic(state.submitForm).then((data) => {
							if (data && data.code === 0) {
								ElMessage.success('保存成功')
								// 列表查询
								loadList()
								state.addOrUpdateVisible = false
							} else {
								ElMessage.error(data.msg)
							}
						}).catch(() => {
							ElMessage.error('保存失败')
						}).finally(() => {
							loading.close()
						})
					}
				}
			})
		}

		return {
			loadList,
			loadListSelect,
			reSetForm,
			reSetFormSelect,
			queryFormRef,
			querySelectFormRef,
			selectionChangeHandle,
			onHandleSizeChange,
			onHandleCurrentChange,
			onSelectSizeChange,
			onSelectCurrentChange,
			formatStatus,
			addOrUpdateHandle,
			updateHandle,
			deleteHandle,
			dataFormSubmit,
			ruleFormRef,
			parentSearch,
			selectParent,
			...toRefs(state),
		}
	}
})
</script>